package us.kg.kotoriforest.springmvc.restful.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import us.kg.kotoriforest.springmvc.restful.dao.EmployeeDao;
import us.kg.kotoriforest.springmvc.restful.pojo.Employee;
import us.kg.kotoriforest.springmvc.restful.service.EmployeeService;

import java.util.List;

/**
 * @author Kotori rotroutine@163.com
 * @since 2025/2/4
 */
@Service
@AllArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
    private final EmployeeDao employeeDao;

    @Override
    public Employee getEmployeeById(long id) {
        return employeeDao.getEmployeeById(id);
    }

    @Override
    public List<Employee> getEmployees() {
        return employeeDao.getAllEmployees();
    }

    @Override
    public boolean addEmployee(Employee employee) {
        return employeeDao.addEmployee(employee) > 0;
    }

    @Override
    public boolean updateEmployeeDirectly(Employee employee) {
        return employeeDao.updateEmployee(employee) > 0;
    }

    @Override
    public boolean updateEmployeeSensitive(Employee employee) {
        return updateEmployeeDirectly(replaceNullValueByRecord(employee));
    }

    @Override
    public boolean deleteEmployeeById(long id) {
        return employeeDao.deleteEmployeeById(id) > 0;
    }

    private Employee replaceNullValueByRecord(Employee employee) {
        Employee employeeData = employeeDao.getEmployeeById(employee.getId());

        // 将employee中的null值替换为employeeData中的值
        if (!StringUtils.hasText(employee.getName())) {
            employee.setName(employeeData.getName());
        }
        if (employee.getAge() == null) {
            employee.setAge(employeeData.getAge());
        }
        if (!StringUtils.hasText(employee.getEmail())) {
            employee.setEmail(employeeData.getEmail());
        }
        if (!StringUtils.hasText(employee.getGender())) {
            employee.setGender(employeeData.getGender());
        }
        if (!StringUtils.hasText(employee.getAddress())) {
            employee.setAddress(employeeData.getAddress());
        }
        if (employee.getSalary() == null) {
            employee.setSalary(employeeData.getSalary());
        }

        return employee;
    }
}
